<?php

namespace factory2;

interface Logger
{
    public function log($msg);
}

class FileLogger implements Logger
{
    public function log($msg)
    {
        echo "文件日志记录：" . $msg;
    }
}

class DatabaseLogger implements Logger
{
    public function log($msg)
    {
        echo "数据库日志记录：" . $msg;
    }
}

class ConsoleLogger implements Logger
{
    public function log($msg)
    {
        echo "控制台日志记录：" . $msg;
    }
}

// 抽象工厂接口：负责创建日志记录器对象
interface LoggerFactory {
    public function createLogger();
}

// 文件日志工厂类
class FileLoggerFactory implements LoggerFactory
{
    public function createLogger(): Logger
    {
        return new FileLogger();
    }
}

// 数据库日志工厂类
class DatabaseLoggerFactory implements LoggerFactory {
    public function createLogger(): Logger
    {
        return new DatabaseLogger();
    }
}

// 控制台日志工厂类
class ConsoleLoggerFactory implements LoggerFactory {
    public function createLogger(): Logger
    {
        return new ConsoleLogger();
    }
}

// 调用（使用工厂创建日志， 不直接new）
class LogService
{
    public function __construct()
    {
    }

    public function makeLog(LoggerFactory $factory, string $msg): void
    {
        $logger = $factory->createLogger();
        $logger->log($msg);
    }
}

$service = new LogService();
// 文件日志使用
$fileLoggerFactory = new FileLoggerFactory();   // 只需要修改service使用的 工厂，即可切换不同的日志记录方式
$service->makeLog($fileLoggerFactory, "文件日志\n");

// 数据库日志使用
$dbLoggerFactory = new DatabaseLoggerFactory();
$service->makeLog($dbLoggerFactory, "数据库日志\n");

// 控制台日志使用
$consoleLoggerFactory = new ConsoleLoggerFactory();
$service->makeLog($consoleLoggerFactory, "控制台日志");